import java.util.ArrayList;
import java.util.List;

/**
 * 平衡二叉树
 *
 * @author Kevin
 * @date 2019-01-01
 */
public class AVLTree<K extends Comparable<K>, V> {

    /**
     * 根节点
     */
    private Node root;

    /**
     * 大小
     */
    private int size;

    public AVLTree() {
        this.root = null;
        this.size = 0;
    }

    public int getSize() {
        return this.size;
    }

    public boolean isEmpty() {
        return this.size == 0;
    }

    /**
     * 判断该二叉树是否是一棵二分搜索树
     */
    public boolean isBST() {
        List<K> keys = new ArrayList<>();
        inOrder(root, keys);
        for (int i = 1; i < keys.size(); i++) {
            if (keys.get(i - 1).compareTo(keys.get(i)) > 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 前序遍历
     *
     * @param node
     * @param keys
     */
    private void inOrder(Node node, List<K> keys) {
        if (node == null) {
            return;
        }

        inOrder(node.left, keys);
        keys.add(node.key);
        inOrder(node.right, keys);
    }

    /**
     * 是否是一棵平衡二叉树
     */
    public boolean isBalanced() {
        return isBalanced(this.root);
    }

    /**
     * 判断以Node为根的二叉树是否是一棵平衡二叉树，递归算法
     *
     * @param node
     * @return
     */
    private boolean isBalanced(Node node) {
        if (node == null) {
            return true;
        }

        int balanceFactor = getBalanceFactor(node);
        if (Math.abs(balanceFactor) > 1) {
            return false;
        }

        return isBalanced(node.left) && isBalanced(node.right);
    }

    /**
     * 获得节点node的高度
     *
     * @param node
     * @return
     */
    private int getHeight(Node node) {
        if (node == null) {
            return 0;
        }

        return node.height;
    }

    /**
     * 获得节点node的平衡因子
     *
     * @param node
     * @return
     */
    private int getBalanceFactor(Node node) {
        if (node == null) {
            return 0;
        }

        return getHeight(node.left) - getHeight(node.right);
    }

    /**
     * 对节点y进行向右旋转操作，返回旋转后新的根节点x
     * y                              x
     * / \                           /   \
     * x   T4     向右旋转 (y)        z     y
     * / \       - - - - - - - ->    / \   / \
     * z   T3                       T1  T2 T3 T4
     * / \
     * T1   T2
     */
    private Node rightRotate(Node y) {
        Node x = y.left;
        Node t3 = x.right;

        // 向右旋转过程
        x.right = y;
        y.left = t3;

        // 更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;

        return x;
    }

    /**
     * 对节点y进行向左旋转操作，返回旋转后新的根节点x
     * y                             x
     * /  \                          / \
     * T1   x      向左旋转 (y)       y    z
     * / \   - - - - - - - ->   / \  / \
     * T2  z                     T1 T2 T3 T4
     * / \
     * T3 T4
     */
    private Node leftRotate(Node y) {
        Node x = y.right;
        Node t2 = x.left;

        // 向左旋转过程
        x.left = y;
        y.right = t2;

        // 更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;

        return x;
    }

    /**
     * 向二分搜索树中添加新的元素(key, value)
     *
     * @param key
     * @param value
     */
    public void add(K key, V value) {
        this.root = add(this.root, key, value);
    }

    /**
     * 向以node为根的二分搜索树中插入元素(key, value)，递归算法
     * 返回插入新节点后二分搜索树的根
     *
     * @param node
     * @param key
     * @param value
     * @return
     */
    private Node add(Node node, K key, V value) {
        if (node == null) {
            this.size++;
            return new Node(key, value);
        }

        if (key.compareTo(node.key) < 0) {
            node.left = add(node.left, key, value);
        } else if (key.compareTo(node.key) > 0) {
            node.right = add(node.right, key, value);
        } else {
            node.value = value;
        }

        // 更新height
        node.height = 1 + Math.max(getHeight(node.left), getHeight(node.right));

        // 计算平衡因子
        int balanceFactor = getBalanceFactor(node);

        // 平衡维护
        // LL
        if (balanceFactor > 1 && getBalanceFactor(node.left) >= 0) {
            return rightRotate(node);
        }

        // RR
        if (balanceFactor < -1 && getBalanceFactor(node.right) <= 0) {
            return leftRotate(node);
        }

        // LR
        if (balanceFactor > 1 && getBalanceFactor(node.left) < 0) {
            node.left = leftRotate(node.left);
            return rightRotate(node);
        }

        // RL
        if (balanceFactor < -1 && getBalanceFactor(node.right) > 0) {
            node.right = rightRotate(node.right);
            return leftRotate(node);
        }

        return node;
    }

    /**
     * 返回以node为根节点的二分搜索树中，key所在的节点
     *
     * @param node
     * @param key
     * @return
     */
    private Node getNode(Node node, K key) {
        if (node == null) {
            return null;
        }

        if (key.equals(node.key)) {
            return node;
        } else if (key.compareTo(node.key) < 0) {
            return getNode(node.left, key);
        } else {
            return getNode(node.right, key);
        }
    }

    /**
     * 是否包含key值的节点
     *
     * @param key
     * @return
     */
    public boolean contains(K key) {
        return getNode(this.root, key) != null;
    }

    /**
     * 根据key获得value值
     *
     * @param key
     * @return
     */
    public V get(K key) {
        Node node = getNode(this.root, key);
        return node == null ? null : node.value;
    }

    /**
     * 设置key的value值
     *
     * @param key
     * @param newValue
     */
    public void set(K key, V newValue) {
        Node node = getNode(this.root, key);
        if (node == null) {
            throw new IllegalArgumentException(key + " doesn't exist!");
        }

        node.value = newValue;
    }

    /**
     * 返回以node为根的二分搜索树的最小值所在的节点
     *
     * @param node
     * @return
     */
    private Node minimum(Node node) {
        if (node.left == null) {
            return node;
        }

        return minimum(node.left);
    }

    /**
     * 删除掉以node为根的二分搜索树中的最小节点
     * 返回删除节点后新的二分搜索树的根
     *
     * @param node
     * @return
     */
    private Node removeMin(Node node) {
        if (node.left == null) {
            Node rightNode = node.right;
            node.right = null;
            this.size--;
            return rightNode;
        }

        node.left = removeMin(node.left);
        return node;
    }

    /**
     * 从二分搜索树中删除键为key的节点
     *
     * @param key
     * @return
     */
    public V remove(K key) {
        Node node = getNode(this.root, key);
        if (node != null) {
            this.root = remove(this.root, key);
            return node.value;
        }

        return null;
    }

    private Node remove(Node node, K key) {
        if (node == null) {
            return null;
        }

        Node resultNode;
        if (key.compareTo(node.key) < 0) {
            node.left = remove(node.left, key);
            resultNode = node;
        } else if (key.compareTo(node.key) > 0) {
            node.right = remove(node.right, key);
            resultNode = node;
        } else {
            // 待删除节点左子树为空的情况
            if (node.left == null) {
                Node rightNode = node.right;
                node.right = null;
                this.size--;
                resultNode = rightNode;
            } else if (node.right == null) {
                // 待删除节点右子树为空的情况
                Node leftNode = node.left;
                node.left = null;
                this.size--;
                resultNode = leftNode;
            } else {
                // 待删除节点左右子树均不为空的情况
                // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
                // 用这个节点顶替待删除节点的位置
                Node successor = minimum(node.right);
                successor.right = remove(node.right, successor.key);
                successor.left = node.left;

                node.left = node.right = null;

                resultNode = successor;
            }
        }

        if (resultNode == null) {
            return null;
        }

        // 更新height
        resultNode.height = 1 + Math.max(getHeight(resultNode.left), getHeight(resultNode.right));

        // 计算平衡因子
        int balanceFactor = getBalanceFactor(resultNode);

        // 平衡维护
        // LL
        if (balanceFactor > 1 && getBalanceFactor(resultNode.left) >= 0) {
            return rightRotate(resultNode);
        }

        // RR
        if (balanceFactor < -1 && getBalanceFactor(resultNode.right) <= 0) {
            return leftRotate(resultNode);
        }

        // LR
        if (balanceFactor > 1 && getBalanceFactor(resultNode.left) < 0) {
            resultNode.left = leftRotate(resultNode.left);
            return rightRotate(resultNode);
        }

        // RL
        if (balanceFactor < -1 && getBalanceFactor(resultNode.right) > 0) {
            resultNode.right = rightRotate(resultNode.right);
            return leftRotate(resultNode);
        }

        return resultNode;
    }

    private class Node {

        /**
         * key值
         */
        public K key;

        /**
         * value值
         */
        public V value;

        /**
         * 左子树和右子树
         */
        public Node left, right;

        /**
         * 高度
         */
        public int height;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
            this.left = null;
            this.right = null;
            this.height = 0;
        }
    }

}
